# -*- coding: utf-8 -*-  
  
from selenium import webdriver  
from selenium.webdriver.common.action_chains import ActionChains
import time,os,webbrowser,sys

reload(sys)
sys.setdefaultencoding('utf-8')
sys.path.append(os.getcwd()+'\\chromedriver.exe')

loginUrl = 'https://login.taobao.com/member/login.jhtml?redirectURL=http%3A%2F%2Fbbs.taobao.com%2F'
driver = webdriver.Chrome()  #可以替换为IE(), FireFox()   
chain = ActionChains(driver)

def autoReply(user,psword,ariticleUrl):
    driver.get(loginUrl) #跳转登录地址
    print(u'跳转登录地址')
    driver.execute_script('document.getElementById("J_LoginBox").className = "login-box no-longlogin module-static"')
    userEle =driver.find_elements_by_name("TPL_username")[0] #写入用户名
    print(u'写入用户名:')
    userEle.clear()
    userEle.send_keys(user)
    time.sleep(1)

    limit =5
    while 'login.taobao.com/member/login.jhtm' in driver.current_url and limit >0:#验证码或密码错误
        print(u'写入密码')
        psEle =driver.find_elements_by_name("TPL_password") #写入密码
        if len(psEle) >0:
            psEle[0].clear()
            psEle[0].send_keys(psword)
            time.sleep(2)
        print(u'获取验证码')
        urlEle =driver.find_elements_by_id("J_StandardCode_m")       #获取验证码
        if len(urlEle)>0:#不可去除，防异常
            lurl = urlEle[0].get_attribute("src")
            if lurl != 'https://assets.alicdn.com/apps/login/static/img/blank.gif':#需验证码
                webbrowser.open_new_tab(lurl)
                lcode = raw_input("LoginCode:")
                codeEles =driver.find_elements_by_id("J_CodeInput_i")
                codeEles[0].send_keys(lcode)   #写入识别的验证码
        print(u'点击登录')
        subEle=driver.find_elements_by_id("J_SubmitStatic")#点击登录
        if len(subEle)>0:#不可去除，防异常
            subEle[0].submit()         
        limit -=1
        time.sleep(3)
    if limit <=0:
        return
    
    print(u'跳转帖子地址:')
    driver.get(ariticleUrl)
    time.sleep(3)
    limit = 5
    while 'sec.taobao.com/query.htm' in driver.current_url and limit>0:
        limit -=1
        urlEle =driver.find_elements_by_id("checkcodeImg")       #获取验证码
        print(u'获取系统繁忙验证码')
        urlBusy = urlEle[0].get_attribute("src")
        webbrowser.open_new_tab(urlBusy)
        bcode = raw_input("BusyCode:")
        codeEles =driver.find_elements_by_id("checkcodeInput")
        codeEles[0].send_keys(bcode)   #写入繁忙验证码
        inputs = driver.find_elements_by_xpath('//*[@id="query"]/div[2]/input')#确定按钮
        inputs[0].submit()
        
def submitContent(ariticleUrl, message):
    #try:
    print(u'写入发表内容:')
    frames =driver.find_elements_by_tag_name("iframe")
    driver.switch_to.frame(frames[0])
    body = driver.find_elements_by_tag_name("body")
    driver.execute_script('document.getElementsByTagName("body")[0].focus()')
    body[0].send_keys(" "+message+" ")                                        #写入发表内容
    time.sleep(5)
    driver.switch_to_default_content()
    print(u'点击发表回复')
    driver.find_elements_by_name("button_publish")[0].click()               #点击发表回复
    time.sleep(3)

    if ariticleUrl in driver.current_url:  #不为http://bbs.taobao.com/catalog/reply_success
        driver.refresh()
        time.sleep(7)

    limit = 5
    while ariticleUrl in driver.current_url and limit >0:  #出现发表回复验证码的处理
        if len(driver.find_elements_by_id("checkCodeInput"))>0:
            driver.execute_script('document.getElementById("checkCodeInput").focus()') #点击获取验证码
            codeEles =driver.find_elements_by_id("J_CheckCodeImg1")
            if len(codeEles) >0:
                rurl =codeEles[0].get_attribute('src')#获取发表回复验证码
                print(u'获取发表回复验证码')
                webbrowser.open_new_tab(rurl)
                rcode = raw_input("ReplyCode:")
                print(u'输入发表回复验证码')
                driver.find_elements_by_id("checkCodeInput")[0].send_keys(rcode)  #输入验证码
        driver.find_elements_by_name("button_publish")[0].click()        #点击发表回复
        print(u'点击发表回复')
        limit -=1
        time.sleep(5)
    #except:
    #    driver.refresh()

if __name__=='__main__':
    user = 'test'
    psword ='test'
    articleUrl = ''
    message = ''
    sleeptime = input('输入顶贴间隔时间:')

    times =100
    index =0
    userList =[]
    userIndex = 0
    messageList =[]
    messageIndex =0
    articleList =[]
    articleIndex =0
    pre ='D:\\pr_python\\singleUserAutoReply\\'
    with open(pre+r'user.txt') as userfile:
        for line in userfile:
            (name,password)=line.split('|')
            userList.append((name,password))
    with open(pre+r'message.txt') as messagefile:
        for line in messagefile:
            messageList.append(line.strip( ))
    with open(pre+r'article.txt') as articlefile:
        for line in articlefile:
            articleList.append(line)
            
    articleUrl =  articleList[articleIndex]
    articleIndex = ( articleIndex+1)%len( articleList)
    
    user = userList[ userIndex][0].decode('utf-8')
    psword =  userList[ userIndex][1].decode('utf-8')
    userIndex = ( userIndex+1)%len( userList)
    
    autoReply(user,psword,articleUrl)
    while index <times:
        index +=1
        message =  messageList[ messageIndex].decode('utf-8')
        messageIndex = ( messageIndex+1)%len( messageList)
        submitContent(articleUrl, message)
        time.sleep(sleeptime)
